package com.hethongviet.vending.pages;

import java.util.List;

import com.hethongviet.vending.Constant;
import com.hethongviet.vending.AppConfig;
import com.hethongviet.vending.R;
import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.CodeResult;
import com.hethongviet.vending.helper.GeneralActivity;
import com.hethongviet.vending.helper.TimerOutUtils;
import com.hethongviet.vending.helper.call.ListenPhoneCallService;
import com.hethongviet.vending.helper.db.ProductSQLite;
import com.hethongviet.vending.helper.db.ProductServiceSQLite;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.helper.dialog.DialogMessageConfirm;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.Product;
import com.hethongviet.vending.model.ProductService;
import com.hethongviet.vending.model.Transaction;
import com.hethongviet.vending.network.CONSTANTS;
import com.hethongviet.vending.network.Network;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class ChangeProductActivity extends GeneralActivity
{
	private Spinner _spinner = null;
	private Button _buttonOk = null;

	private TimerOutUtils _timerOutUtils = null;
	private int _numberFinish = 0;

	private ProductSQLite _productSqLite = null;

	private ProductServiceSQLite _productServiceSQLite = null;

	public ChangeProductActivity()
	{
		_productSqLite = new ProductSQLite(this);
		_productServiceSQLite = new ProductServiceSQLite(
				ChangeProductActivity.this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		/* Full screen */
		Utils.prepareWindow(this);

		_numberFinish = getIntent().getIntExtra(Constant.EXTRA_FINISH, 2);

		setContentView(R.layout.page_change_product);

		findViewById(R.id.button_dialog_cancel).setOnClickListener(
				new OnClickListener()
				{
					@Override
					public void onClick(View arg0)
					{
						setResult(RESULT_CANCELED);
						finish();
					}
				});

		((TextView) findViewById(R.id.text_user_name)).setVisibility(View.GONE);

		final List<Product> productsList = _productSqLite.getAll();
		final int length = productsList.size();
		final String arrayString[] = new String[length];

		for (int i = 0; i < length; i++)
		{
			arrayString[i] = productsList.get(i).getName();
		}
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, arrayString);

		_spinner = (Spinner) findViewById(R.id.input_spiner);
		_spinner.setAdapter(arrayAdapter);

		_buttonOk = (Button) findViewById(R.id.button_dialog_ok);
		_buttonOk.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Box currentBox = AppMain.getInstance().getListBoxItems().get(
						AppMain.getInstance().getCurrentBoxItemIndex()).getBox();

				/* Insert product take out */
				ProductService productService = new ProductService();

				Utils.debug("Add/change product");

				if (currentBox.getProductAmount() > 0)
				{
					Utils.debug("change product --- first take out");

					productService.setTransaction(ProductService.TRANSACTION_PRODUCT_TAKE_OUT);
					productService.setAmount(currentBox.getProductAmount());
					productService.setIdBox(currentBox.getId());
					productService.setCodeProduct(currentBox.getProductCode());
					productService.setMachineCode(AppMain.getInstance().getMachineInfo().getCode());
					productService.setPrice(currentBox.getProductPrice());
					productService.setSentServerOk(false);
					productService.setStaffChecker(AppMain.getInstance().getCurrentAccount().getId());
					productService.setStaffService(AppMain.getInstance().getCurrentAccount().getId());
					productService.setDate(System.currentTimeMillis());

					_productServiceSQLite.insert(productService);

					if (!AppConfig.USE_SEND_ALL_DATA)
					{
						if (AppConfig.IS_NETWORK_AVAILABLE)
						{
							_productServiceSQLite.updateIdDB(productService);
							Network.sendProductTakeOut(productService);
						}
					}
				}

				AppMain.getInstance().getListBoxItems().get(
						AppMain.getInstance().getCurrentBoxItemIndex()).setProduct(
						productsList.get(_spinner.getSelectedItemPosition()));

				AppMain.getInstance().getListBoxItems().get(
						AppMain.getInstance().getCurrentBoxItemIndex()).getBox().setProductAmount(
						0);

				AppMain.getInstance().getListBoxItems().get(
						AppMain.getInstance().getCurrentBoxItemIndex()).getBox().setProductCode(
						productsList.get(_spinner.getSelectedItemPosition()).getCode());

				setResult(RESULT_OK);

				finish();
			}
		});

		startService(new Intent(this, ListenPhoneCallService.class));

		_timerOutUtils = new TimerOutUtils(this, R.id.text_time, false);
	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		_timerOutUtils.startTimerNotOperating();

		return super.onTouchEvent(event);
	}

	@Override
	protected void onResume()
	{
		_timerOutUtils.startTimerOutUser();
		_timerOutUtils.startTimerNotOperating();
		super.onResume();
	}

	@Override
	protected void onPause()
	{
		_timerOutUtils.stop();
		super.onPause();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (AppMain.getInstance().getCodeResult())
		{
			case TIME_OUT_NOT_OPERATOR:
				try
				{
					AppMain.getInstance().setNumberActivityFinishLogout(
							_numberFinish);
					showDialog(R.string.message_time_out_user_not_operating);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			case TIME_OUT_USER:
				try
				{
					AppMain.getInstance().setNumberActivityFinishLogout(
							_numberFinish);
					showDialog(R.string.message_time_out_user);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
				break;
			default:
				break;
		}

		AppMain.getInstance().setCodeResult(CodeResult.NONE);

		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_time_out_user)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_time_out_user_not_operating)
		{

			final DialogMessageConfirm dialogMessageConfirmNotOperating = new DialogMessageConfirm(
					this, false, id, true);
			OnClickListener onClickListenerYESNotOperating = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmNotOperating.cancel();
					_timerOutUtils.stopTimeOutDialog();
					AppMain.getInstance().setNumberActivityFinishLogout(0);
				}
			};
			dialogMessageConfirmNotOperating.setOnclickListenerYes(onClickListenerYESNotOperating);
			return dialogMessageConfirmNotOperating;
		}
		else
			return super.onCreateDialog(id);
	}

	@Override
	public void onConnectFail(int typeError)
	{
	}

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{
		if (transaction == null)
		{
			Utils.debug("Null -----------received");
			return;
		}

		final String message = transaction.getMessageReceived();
		Utils.debug("Receive message = " + message);

		if (message == null || message.equals(""))
		{
			Utils.debug("Null message!!!!!!!!");
			return;
		}

		if (transaction.getModel() == null)
		{
			Utils.debug("Model null------------");
		}

		if (transaction.getMethodSent().equals(
				CONSTANTS.SERVICE.ADD_PRODUCT_TAKEOUT))
		{
			if (transaction.getMessageReceived().toUpperCase().contains("OK"))
			{
				ProductService productService = (ProductService) transaction.getModel();
				productService.setSentServerOk(true);
				_productServiceSQLite.insert(productService);
			}
		}
	}
}
